//
//  InviteCodeModel.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/2/26.
//

import Foundation
import Vapor
import Fluent
import FluentSQL
final class InviteCodeModel: Model, Content {
    static var schema: String {
        return "invite_codes"
    }
    
    @ID(custom: .id)
    var id: UUID?
    
    @Field(key: FieldKeys.code)
    var code: String
    
    @Field(key: FieldKeys.inviterID)
    var inviterID: String
    
    @Field(key: FieldKeys.groupID)
    var groupID: String
    
    @Field(key: FieldKeys.expiryDate)
    var expiryDate: Date
    
    @Field(key: FieldKeys.inviteeID)
    var inviteeID: String
    
    @Field(key: FieldKeys.inviteDate)
    var inviteDate: Date
    
    init() { }
    
    init(id: UUID? = nil, code: String, inviterID: String, groupID: String, expiryDate: Date, inviteeID: String, inviteDate: Date) {
        self.id = id
        self.code = code
        self.inviterID = inviterID
        self.groupID = groupID
        self.expiryDate = expiryDate
        self.inviteeID = inviteeID
        self.inviteDate = inviteDate
    }
}

extension InviteCodeModel {
    struct FieldKeys {
        static var id: FieldKey { "invite_codes_id" }
        static var code: FieldKey { "invite_codes_invite_code" }
        static var inviterID: FieldKey { "invite_codes_inviter_id" }
        static var groupID: FieldKey { "invite_codes_group_id" }
        static var expiryDate: FieldKey { "invite_codes_expiry_date" }
        static var inviteeID: FieldKey { "invite_codes_invitee_id" }
        static var inviteDate: FieldKey { "invite_codes_invite_date" }
    }
}

struct InviteCodeModelMigration: AsyncMigration {
    func prepare(on database: Database) async throws {
        try await database.schema(InviteCodeModel.schema)
            .id()
            .field(InviteCodeModel.FieldKeys.code, .string, .required, .custom("COMMENT '邀请码'"))
            .field(InviteCodeModel.FieldKeys.inviterID, .string, .required, .custom("COMMENT '邀请人ID'"))
            .field(InviteCodeModel.FieldKeys.groupID, .string, .required, .custom("COMMENT '邀请加入的群组ID'"))
            .field(InviteCodeModel.FieldKeys.expiryDate, .custom("datetime(0)"), .required, .custom("COMMENT '过期时间'"))
            .field(InviteCodeModel.FieldKeys.inviteeID, .string, .custom("COMMENT '被邀请人ID'"))
            .field(InviteCodeModel.FieldKeys.inviteDate, .custom("datetime(0)"), .sql(.default(SQLFunction("now"))) , .required, .custom("COMMENT '邀请日期'"))
            .create()
    }
    
    func revert(on database: Database) async throws {
        try await database.schema(InviteCodeModel.schema).delete()
    }
}

